<?php
/**
 * PHP version 5
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    Textbook
 * @subpackage Textbook
 * @author     Aljaz Srebrnic <a2piratesoft@gmail.com>
 * @author     E. Pavletič
 * @copyright  2008 a2PirateSoftware
 * @license    GPL License v3 <http://www.gnu.org/copyleft/gpl.html>
 */

require_once("class.CommonAction.php");
require_once(ZNF::MODULES_DIR.'/Textbook/Business/TextbookDAO.php');
require_once('ZNF/Presentation/Smarty.php');

class Textbook_Action_Textbook extends CommonAction {

  private $textbookDao;

  /**
   * Constructor
   *
   * @access public
   */
  public function __construct(){
    parent::__construct();
    $this->textbookDao = new TextbookDAO();
  }


  /**
   * Metoda textbookSearchForm
   *
   * Metoda prikaže obrazec za iskanje učbenikov. Njena edina naloga je, da nastavi ključ za zaščito pred roboti.
   **/
  public function textbookSearchForm($form, $mapping) {
    // Pošlje odjemalcu piškotek (cookie) s kodo za preprečevanje avtomatskih vnosov
    $_REQUEST['key'] = self::sendToken(true);

    return $mapping->findForward('success');
  }


  /**
   * Metoda textbookSearchFormSubmit
   *
   * Metoda poišče učbenike, ki zadoščajo pogojem in jih prikaže v obliki seznama
   **/
  public function textbookSearchFormSubmit($form, $mapping) {
    $page = isset($_GET['pageID']) ? intval($_GET['pageID']) : 1;
    $offset = Constants::$limit * ($page-1); //Stran 1 je v resnici stran 0 :-D

    try {
      // Poišče v bazi učbenike, ki zadoščajo pogojem
      $total = $this->textbookDao->countSearchedTextbooks($form->getIsbn(), $form->getTitleArray(), $form->getAuthorsArray(), $form->getPublisher());
      $textbooks = $this->textbookDao->searchTextbooks((isset($_SESSION['id']) ? $_SESSION['id'] : null), $form->getIsbn(), $form->getTitleArray(), $form->getAuthorsArray(), $form->getPublisher(), $offset, Constants::$limit);
    } catch (TextbookDAOException $e){
      $_REQUEST['errors'] = self::handleException($e, 'Textbook');
      return $mapping->findForward('failure');
    }
    
    if (isset($textbooks)) { // Učbenik je prisoten v bazi
      $_REQUEST['pageID'] = $page;
      $_REQUEST['textbooks'] = $textbooks;
      $_REQUEST['isbn'] = $form->getIsbn();
      $_REQUEST['title'] = stripslashes(stripslashes($form->getTitle()));
      $_REQUEST['authors'] = stripslashes(stripslashes($form->getAuthors()));
      $_REQUEST['publisher'] = stripslashes(stripslashes($form->getPublisher()));
      $_REQUEST['pager'] = $this->getPagerLinks($total, 'textbook', 'textbookSearchFormSubmit');
      $_REQUEST['saved'] = false;
      if ($_SESSION['znf']['authenticated'])
 	$_REQUEST['authenticated'] = true;
    } else {                        // Knjiga, ki jo uporabnik išče, ni prisotna v bazi. V primeru, da je uporabnik vnesel tudi ISBN, si ga sistem zabeleži,
      if (isset($_SESSION['id']) && // tako da lahko v bodoče lahko obvesti uporabnika o novih vnosih iskanega učbenika
	  !is_null($form->getIsbn())) { 
	try {
	  $this->textbookDao->rememberRequest($_SESSION['id'], $form->getIsbn());
	  $_REQUEST['saved'] = true;
	} catch(TextbookDAOException $e) {
	  self::handleException($e, 'Textbook');
	}
      }
    }

    return $mapping->findForward('success');
  }


  /**
   * Metoda contact
   *
   * Metoda poišče podatke o učbeniku, ki ga je izbral uporabnik. Podatki bodo prikazani v obrazcu za sporočanje lastniku
   *
   * @access public
   */
  public function contact($form, $mapping) {
    // V primeru, da uporabnik ali skrbnik spreminja že obstoječo knjigo, naloži podatke. Uporabnik mora biti overjen.
    $textbook = null;
    if (isset($_GET['id'])) {
      try {
	$textbook = $this->textbookDao->getById($_GET['id']);
	require_once(ZNF::MODULES_DIR.'/User/Business/UserDAO.php');
	$userDao = new User_Business_UserDAO();
	$user = $userDao->getById($_SESSION['id']);
      } catch(TextbookDAOException $e) {
	$_REQUEST['errors'] = self::handleException($e, 'Textbook');
	return $mapping->findForward('failure');
      }
    }

    if (is_null($textbook)) {
      $translation = new ZNF_Presentation_Translation('Textbook', $_SESSION['znf']['lang']);
      $errors = new ZNF_Action_ActionErrors();
      
      $errors->addError(1, $translation->get('errorTextbookLoad'));
      $_REQUEST['errors'] = $errors;

      return $mapping->findForward('failure');
    }

    $_REQUEST['textbook'] = $textbook;
    $_REQUEST['user'] = $user;
    $_REQUEST['isbn'] = $form->getIsbn();
    $_REQUEST['title'] = $form->getTitle();
    $_REQUEST['authors'] = $form->getAuthors();
    $_REQUEST['publisher'] = $form->getPublisher();
     
    return $mapping->findForward('success');
  }


  /**
   * Metoda contactSubmit
   *
   * Metoda pošlje uporabnikovo sporočilo lastniku učbenika
   *
   * @access public
   */
  public function contactSubmit($form, $mapping) {
    require_once(ZNF::MODULES_DIR.'/User/Business/UserDAO.php');

    $smarty = new ZNF_Presentation_Smarty('Textbook', $mapping);
    $translation = new ZNF_Presentation_Translation('Textbook', $_SESSION['znf']['lang']);

    try {
      $userDao = new User_Business_UserDAO();
      $user = $userDao->getById($form->getUserId());
    } catch(TextbookDAOException $e) {
      $_REQUEST['errors'] = self::handleException($e, 'Textbook');
      return $mapping->findForward('failure');
    }
    
    $smarty->assign('message', str_replace("\n", "<br />",$form->getMessage()));
    $smarty->assign('email', $form->getEmail());

    if (!is_null($form->getPhone()))
      $smarty->assign('phone', $form->getPhone());
    if (!is_null($form->getCell()))
      $smarty->assign('cell', $form->getCell());
    if (!is_null($form->getSkype()))
      $smarty->assign('skype', $form->getSkype());
    if (!is_null($form->getIcq()))
      $smarty->assign('icq', $form->getIcq());
    if (!is_null($form->getMsn()))
      $smarty->assign('msn', $form->getMsn());

    try{
      $this->sendEmail($user['name'], $user['surname'], $user['email'], $translation->get('contactMessageSubject'), $smarty->fetch("contactEmail.tpl"));
    } catch (ZNF_Action_ActionException $e) {
      $_REQUEST['errors'] = self::handleException($e, 'Textbook');
      return $mapping->findForward('failure');
    }

    return $mapping->findForward('success');
  }


  /**
   * Metoda textbookList
   *
   * Metoda prikaže seznam uporabnikovih  ušbenikov. V primeru, da je uporabnik tudi skrbnik aplikacije,
   * prikaže učbenike vseh uporabnikov. Na vsaki strani bo prikazala  Constants::limit učbenikov (uporabi pager).
   **/
  public function textbookList($form, $mapping) {
    $page = isset($_GET['pageID']) ? intval($_GET['pageID']) : 1;
    $offset = Constants::$limit * ($page-1); //Stran 1 je v resnici stran 0 :-D

    try {
      // V primeru, da je uporabnik skrbnik, prikaže vse učbenike (id uporabnika postavi na null), razen če ni prisoten v POSTu parameter "id".
      // Njegova prisotnost namreč pomeni, da uporabnik je tudi skrbnik in da išče učbenike nekega uporabnika z uporabo iskalnega obrazca
      // Prisotnost parametra $_GET['userId'] pomeni, da je uporabnik skrbnik, ki klika na povezavo v pagerju. "userId" je identifikator uporabnika, katerega učbenike išče skrbnik
      $userId = isset($_REQUEST['userId']) ? intval($_REQUEST['userId']) : null;
      $userId = in_array('admin', $_SESSION['znf']['roles']) ? $userId : $_SESSION['id'];

      $total = $this->textbookDao->countTextbooks($userId);
      $textbooks = $this->textbookDao->getAll($userId, $offset, Constants::$limit);
    } catch (TextbookDAOException $e){
      $_REQUEST['errors'] = self::handleException($e, 'Textbook');
      return $mapping->findForward('failure');
    }

    if (isset($_REQUEST['fp']) && ($_REQUEST['fp'] == 't')) // Prikaže celo stran?
      $_REQUEST['fullPage'] = true;
    $_REQUEST['pageID'] = $page;
    if (isset($userId))
      $_REQUEST['userId'] = $userId;

    $_REQUEST['textbooks'] = $textbooks;
    $_REQUEST['pager'] = $this->getPagerLinks($total, 'textbook', 'textbookList', (($userId !== null) ?'&userId='.$userId : ''));

    return $mapping->findForward('success');
  }


  /**
   * Metoda textbookFormDisplay
   *
   * Metoda prikaze obrazec za vnos oz. spreminjanje učbenika.
   *
   * @access public
   */
  public function textbookFormDisplay($form, $mapping) {
    // V primeru, da uporabnik ali skrbnik spreminja že onstoječo knjigo, naloži podatke. Uporabnik mora biti overjen.
    if (($_SESSION['znf']['authenticated']) && isset($_GET['id'])) {
      try {
	$textbook = $this->textbookDao->getById($_GET['id']);
      } catch(TextbookDAOException $e) {
	$_REQUEST['errors'] = self::handleException($e, 'Textbook');
	return $mapping->findForward('failure');
      }
      if ($textbook != null)
	$_REQUEST['textbook'] = $textbook;
    }
     
    return $mapping->findForward('success');
  }


  /**
   * Metoda textbookFormSubmit
   *
   * Metoda vnese v pod. bazo podatke o učbeniku. V primeru, da je učbenik že prisoten v bazi (id != null), spremeni obstoječe podatke, sicer ustvati nov tuple
   *
   * @access public
   */
  public function textbookFormSubmit($form, $mapping) {
    // Najprej izbriše iz baze vse zahteve po učbenikih, ki so starejše od Constants::$searchedTextbooksRetainPeriod dni
    // V primeru napake jo zabečeži v log in nadaljuje z izvajanjem. Bo pač zahteve izbrisal naslednjič.
    try {
      $this->textbookDao->deleteOldSearchedTextbooks(Constants::$searchedTextbooksRetainPeriod);
    } catch(TextbookDAOException $e) {
      self::handleException($e, 'Textbook');
    }
	
    // Naslednji stavki izbrišejo iz baze vse učbenike starejše od Constants::$textbooksRetainPeriod dni. V primeru napake,
    // je ne sporoči uporabniku, ampak jo samo zabeleži v log-u
    try{
      $this->textbookDao->deleteOldTextbooks(Constants::$textbooksRetainPeriod);
    } catch (ZNF_Action_ActionException $e) {
      self::handleException($e, 'Textbook');
    }

    try {
      if ($form->getId() !== null) {
	$this->textbookDao->updateTextbook($form);
        $_REQUEST['fullPage'] = true;
	return $mapping->findForward('successList');
      } else {
 	$this->textbookDao->insertTextbook($form);

	// Pošlje sporočilo o novem učbeniku vsem, ki so ga do tega trenutka iskali.
	$textbookSeekers = $this->textbookDao->getTextbookSeekers($form->getIsbn());
	if (count($textbookSeekers) > 0) {
	  $smarty = new ZNF_Presentation_Smarty('Textbook', $mapping);
	  $translation = new ZNF_Presentation_Translation('Textbook', $_SESSION['znf']['lang']);
	  $smarty->assign('isbn', $form->getIsbn());
	  $smarty->assign('title', $form->getTitle());
	  $smarty->assign('authors', $form->getAuthors());
	  $smarty->assign('publisher', $form->getPublisher());
	  $smarty->assign('sitename', Constants::$sitename);
	  $smarty->assign('siteUrl', Constants::$siteUrl);
	  foreach ($textbookSeekers as $tbSeeker) {
	    $smarty->assign('name', $tbSeeker['name']);
	    $smarty->assign('surname', $tbSeeker['surname']);

	    try{
	      $this->sendEmail($tbSeeker['name'], $tbSeeker['surname'], $tbSeeker['email'], $translation->get('newTextbookSubject'), $smarty->fetch("newTextbookEmail.tpl"));
	    } catch (ZNF_Action_ActionException $e) {
	      self::handleException($e, 'Textbook');
	    }
	  }
	}

	return $mapping->findForward('successInsert');
      }
    } catch(TextbookDAOException $e) {
      $_REQUEST['errors'] = self::handleException($e, 'Textbook');
      return $mapping->findForward('failure');
    }
  }


  /**
   * Metoda deleteTextbooks
   *
   * Metoda izbriše učbenike iz podatkovne baze
   *
   * @access public
   */
  public function deleteTextbooks($form, $mapping) {
    if (count($_POST['delete']) == 0) {
      $translation = new ZNF_Presentation_Translation('Textbook', $_SESSION['znf']['lang']);
      $errors = new ZNF_Action_ActionErrors();
      
      $errors->addError(1, $translation->get('errorNoTextbookSelected'));
      $_REQUEST['errors'] = $errors;

      return $mapping->findForward('failure');
    }

    $userIdList = '';
    foreach($_POST['delete'] as $userId)
      $userIdList .= "'".intval($userId)."', ";
    $userIdList = substr($userIdList, 0, strlen($userIdList)-2);

    try {
      $this->textbookDao->deleteTextbooks($userIdList);
    } catch(TextbookDAOException $e) {
      $_REQUEST['errors'] = self::handleException($e, 'Textbook');
      return $mapping->findForward('failure');
    }

    return $mapping->findForward('success');
  }
}
?>
